<template>
  <base-table-layout
    title="设备管理"
    :total="total"
    :current-page="currentPage"
    :page-size="pageSize"
    @update:currentPage="val => currentPage = val"
    @update:pageSize="val => pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-input
        v-model="searchForm.sensorName"
        placeholder="设备名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-select 
        v-model="searchForm.cultivateId" 
        placeholder="选择育苗点"
        style="width: 200px; margin-left: 10px;"
        clearable
        filterable
        @change="handleSearch"
      >
        <el-option
          v-for="item in nurseryOptions"
          :key="item.deptId"
          :label="item.deptName"
          :value="item.deptId"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        @click="resetSearch"
      >重置</el-button>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增设备</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
        v-loading="loading"
        :data="sensorList"
        border
        style="width: 100%"
      >
        <el-table-column prop="sensorId" label="设备ID" width="150" />
        <el-table-column prop="sensorName" label="设备名称" min-width="180" />
        <el-table-column prop="expireTime" label="到期时间" width="150" />
        <el-table-column prop="restFlow" label="剩余流量" width="150" />
        <el-table-column prop="capability" label="设备类型" width="150">
          <template slot-scope="scope">
            {{ scope.row.capability === 1 ? '单温度' : '温湿度一体' }}
          </template>
        </el-table-column>
        <el-table-column label="育苗点" min-width="200">
          <template slot-scope="scope">
            {{ getNurseryName(scope.row.cultivateId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <!-- 新增/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item v-if="!isEdit" label="设备ID" prop="sensorId">
            <el-input v-model="form.sensorId" placeholder="请输入设备ID" />
          </el-form-item>
          <el-form-item label="设备名称" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入设备名称" />
          </el-form-item>
          <template v-if="isEdit">
            <el-form-item label="设备类型" prop="capability">
              <el-select v-model="form.capability" placeholder="请选择设备类型">
                <el-option label="单温度" :value="1" />
                <el-option label="温湿度一体" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="育苗点" prop="cultivateId">
              <el-select 
                v-model="form.cultivateId" 
                placeholder="请选择育苗点"
                filterable
              >
                <el-option
                  v-for="item in nurseryOptions"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import BaseTableLayout from '@/components/BaseTableLayout.vue'

export default {
  name: 'SensorManager',
  components: {
    BaseTableLayout
  },
  data() {
    return {
      loading: false,
      searchForm: {
        sensorName: '',
        cultivateId: undefined
      },
      allSensorList: [], // 存储所有设备数据
      sensorList: [], // 存储当前页显示的设备数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      isEdit: false,
      form: {
        sensorId: '',
        nickName: '',
        capability: '',
        cultivateId: ''
      },
      rules: {
        sensorId: [
          { required: true, message: '请输入设备ID', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' }
        ],
        capability: [
          { required: true, message: '请选择设备类型', trigger: 'change' }
        ],
        cultivateId: [
          { required: true, message: '请选择育苗点', trigger: 'change' }
        ]
      },
      nurseryOptions: []
    }
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑设备' : '新增设备'
    },
    // 根据搜索条件过滤数据
    filteredSensorList() {
      return this.allSensorList.filter(sensor => {
        const nameMatch = !this.searchForm.sensorName || 
          sensor.sensorName.toLowerCase().includes(this.searchForm.sensorName.toLowerCase())
        
        const cultivateMatch = !this.searchForm.cultivateId || 
          Number(sensor.cultivateId) === Number(this.searchForm.cultivateId)
        
        return nameMatch && cultivateMatch
      })
    }
  },
  watch: {
    // 监听筛选条件变化，更新分页数据
    filteredSensorList: {
      handler(val) {
        this.total = val.length
        this.updatePageData()
      },
      immediate: true
    }
  },
  created() {
    this.fetchNurseryOptions()
    this.fetchSensorList()
  },
  methods: {
    // 获取育苗点选项
    async fetchNurseryOptions() {
      try {
        const response = await request.get('/departments/page', {
          params: {
            deptType: 4,
            pageSize: 999
          }
        })
        if (response && response.records) {
          this.nurseryOptions = response.records
        }
      } catch (error) {
        console.error('获取育苗点列表失败:', error)
        this.$message.error('获取育苗点列表失败')
      }
    },

    // 获取育苗点名称
    getNurseryName(cultivateId) {
      const nursery = this.nurseryOptions.find(item => item.deptId === cultivateId)
      return nursery ? nursery.deptName : '-'
    },

    // 获取设备列表
    async fetchSensorList() {
      try {
        this.loading = true
        const response = await request.get('/sensors')
        // 确保cultivateId是数字类型
        this.allSensorList = (response || []).map(sensor => ({
          ...sensor,
          cultivateId: Number(sensor.cultivateId)
        }))
        this.updatePageData()
      } catch (error) {
        console.error('获取设备列表失败:', error)
        this.$message.error('获取设备列表失败')
      } finally {
        this.loading = false
      }
    },

    // 更新当前页数据
    updatePageData() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.sensorList = this.filteredSensorList.slice(start, end)
    },

    handleSearch: _.debounce(function() {
      this.currentPage = 1
      this.updatePageData()
    }, 300),

    resetSearch() {
      this.searchForm = {
        sensorName: '',
        cultivateId: undefined
      }
      this.currentPage = 1
      this.updatePageData()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.updatePageData()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.updatePageData()
    },

    // 显示新增对话框
    handleAdd() {
      this.isEdit = false
      this.form = {
        sensorId: '',
        nickName: '',
        capability: '',
        cultivateId: ''
      }
      this.dialogVisible = true
    },

    // 显示编辑对话框
    handleEdit(row) {
      this.isEdit = true
      this.form = {
        sensorId: row.sensorId,
        nickName: row.sensorName,
        capability: row.capability,
        cultivateId: row.cultivateId
      }
      this.dialogVisible = true
    },

    // 删除设备
    handleDelete(row) {
      this.$confirm('确认删除该设备吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await request.delete(`/sensors/${row.sensorId}`)
          this.$message.success('删除成功')
          this.fetchSensorList()
        } catch (error) {
          console.error('删除设备失败:', error)
          this.$message.error('删除设备失败')
        }
      }).catch(() => {})
    },

    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.form.validate()
        if (this.isEdit) {
          // 编辑设备 - 使用JSON格式请求体
          await request.put(`/sensors`, {
            sensorId: this.form.sensorId,
            nickName: this.form.nickName,
            capability: this.form.capability.toString(),
            cultivateId: this.form.cultivateId.toString()
          })
          this.$message.success('编辑成功')
        } else {
          // 新增设备 - 使用query参数
          await request.post(`/sensors?sensorId=${encodeURIComponent(this.form.sensorId)}&nickName=${encodeURIComponent(this.form.nickName)}`)
          this.$message.success('添加成功')
        }
        this.dialogVisible = false
        this.fetchSensorList()
      } catch (error) {
        if (error !== false) {
          console.error(this.isEdit ? '编辑设备失败:' : '添加设备失败:', error)
          this.$message.error(this.isEdit ? '编辑设备失败' : '添加设备失败')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.filter-item {
  margin-left: 10px;
}
</style> 